import 'package:dio/dio.dart';
import '../models/dateline_event.dart';

/// 日历事件类型服务
class DateLineTypeService {
  final Dio _dio;

  /// 构造函数
  DateLineTypeService(this._dio);

  /// 获取所有日历事件类型
  Future<List<DatelineEventType>> getAllDateLineTypes() async {
    try {
      print('正在获取所有日历事件类型......');
      print('Dio 实例: $_dio');
      print('Dio baseUrl: ${_dio.options.baseUrl}');

      // 调用后端接口获取所有类型
      print('开始发送 GET 请求到 /api/dateline/type/list');
      final response = await _dio.get('/api/dateline/type/list');
      print('GET 请求完成，状态码: ${response.statusCode}');

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        print('响应数据: $responseData');

        if (responseData is Map<String, dynamic>) {
          // 检查响应格式
          if (responseData.containsKey('data') && responseData['data'] is List) {
            final List<dynamic> typesData = responseData['data'];
            print('解析类型数据，共 ${typesData.length} 个');
            return typesData
                .map((typeData) => _parseTypeFromJson(typeData))
                .toList();
          }
        } else if (responseData is List) {
          print('响应是列表格式，共 ${responseData.length} 个');
          return responseData
              .map((typeData) => _parseTypeFromJson(typeData))
              .toList();
        }
      }

      print('返回空列表');
      return [];
    } catch (e) {
      print('获取日历事件类型异常: $e');
      print('异常堆栈: ${StackTrace.current}');
      return [];
    }
  }

  /// 根据ID获取日历事件类型详情
  Future<DatelineEventType?> getDateLineTypeDetail(int typeId) async {
    try {
      print('正在获取日历事件类型详情: $typeId');

      // 调用后端接口获取类型详情
      final response = await _dio.get('/api/dateline/type/get/$typeId');

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;

        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('data') && responseData['data'] is Map) {
            return _parseTypeFromJson(responseData['data']);
          }
        } else if (responseData is Map<String, dynamic>) {
          return _parseTypeFromJson(responseData);
        }
      }

      return null;
    } catch (e) {
      print('获取日历事件类型详情异常: $e');
      return null;
    }
  }

  /// 创建日历事件类型
  Future<bool> createDateLineType(String name, int type) async {
    try {
      print('正在创建日历事件类型: $name');

      // 准备请求数据
      final requestData = {
        'name': name,
        'type': type,
      };

      // 调用后端接口创建类型
      final response = await _dio.post(
        '/api/dateline/type/create',
        data: requestData,
      );

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;

        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('code')) {
            final code = responseData['code'];
            if (code == 200 || code == '200') {
              print('创建日历事件类型成功');
              return true;
            }
          }
        }
      }

      return false;
    } catch (e) {
      print('创建日历事件类型异常: $e');
      return false;
    }
  }

  /// 更新日历事件类型
  Future<bool> updateDateLineType(int id, String name, int type) async {
    try {
      print('正在更新日历事件类型: $id');

      // 准备请求数据
      final requestData = {
        'id': id,
        'name': name,
        'type': type,
      };

      // 调用后端接口更新类型
      final response = await _dio.post(
        '/api/dateline/type/update',
        data: requestData,
      );

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;

        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('code')) {
            final code = responseData['code'];
            if (code == 200 || code == '200') {
              print('更新日历事件类型成功');
              return true;
            }
          }
        }
      }

      return false;
    } catch (e) {
      print('更新日历事件类型异常: $e');
      return false;
    }
  }

  /// 删除日历事件类型
  Future<bool> deleteeDateLineType(int id) async {
    try {
      print('正在删除日历事件类型: $id');

      // 调用后端接口删除类型
      final response = await _dio.delete('/api/dateline/type/delete/$id');

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;

        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('code')) {
            final code = responseData['code'];
            if (code == 200 || code == '200') {
              print('删除日历事件类型成功');
              return true;
            }
          }
        }
      }

      return false;
    } catch (e) {
      print('删除日历事件类型异常: $e');
      return false;
    }
  }

  /// 从 JSON 解析事件类型
  DatelineEventType _parseTypeFromJson(dynamic typeData) {
    if (typeData is! Map<String, dynamic>) {
      throw Exception('Invalid type data format');
    }

    final id = typeData['type'] ?? typeData['id'] ?? 1;

    // 根据 ID 返回对应的枚举值
    for (final type in DatelineEventType.values) {
      if (type.id == id) {
        return type;
      }
    }

    // 如果没有找到匹配的类型，返回默认的"其他"类型
    return DatelineEventType.other;
  }
}
